import * as sass from 'sass'
import fs from 'fs'
import { resolve } from 'path'
import glob from 'fast-glob'
import chalk from 'chalk'

const step = (text, color) => console.log(chalk[color](text))

const buildCss = async dir => {
  const outPath = resolve('dist/' + dir)
  const files = await glob(`packages/${dir}/**/*.scss`, { onlyFiles: true })
  const filesInfo = files.map(item => {
    const list = item.split('/')
    const listLength = list.length
    let name = list[listLength - 2]
    return {
      name,
      path: item
    }
  })
  return new Promise(r => {
    fs.stat(outPath, async err => {
      if (err) {
        await fs.mkdirSync(outPath)
      }

      for (let i of filesInfo) {
        const css = await sass.renderSync({ file: i.path, outputStyle: 'compressed' })
        await fs.writeFileSync(`${outPath.replace(`/${i.name}`, '')}/${i.name}/index.css`, css.css.toString())
        step('分离 ' + i.path, 'gray')
      }
      r()
    })
  })
}

export default buildCss
